package edu.ynu.onlinesqltool.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.ynu.onlinesqltool.model.Field;
import edu.ynu.onlinesqltool.model.Table;

public class TableDao {
	private static DaoHelper daoHelper = DaoHelperImpl.getBaseDaoInstance();
	public static List ShowTable(){
		String sql = "show tables";
		Connection conn = daoHelper.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		ArrayList tables = new ArrayList();
		try{
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while(rs.next()){
				String name = rs.getString(1);
				tables.add(name);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			daoHelper.closeConnection(conn);
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeResult(rs);
		}
		return tables;
	}
	public static Table DescribeTable(String tableName){
		String sql = "describe "+tableName;
		Connection conn = daoHelper.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			Table table = new Table();
			ArrayList fields = new ArrayList();
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while(rs.next()){
				Field field = new Field();
				field.setName(rs.getString("Field"));
				field.setType(rs.getString("Type"));
				field.setIsNull(rs.getString("Null"));
				field.setKey(rs.getString("Key"));
				field.setDefault(rs.getString("Default"));
				field.setExtra(rs.getString("Extra"));
				fields.add(field);
			}
			table.setName(tableName);
			table.setFields(fields);
			return table;
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			daoHelper.closeConnection(conn);
			daoHelper.closePreparedStatement(stmt);
			daoHelper.closeResult(rs);
		}
		return null;
	}
}
